Create a Real-Time Clock in JavaScript with Date and Milliseconds

Faraz

By Faraz -

Learn how to create a real-time clock using JavaScript. Step-by-step guide with code examples to display the date, time, and milliseconds on your website.


create a real-time clock in javascript with date and milliseconds.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Conclusion
  6. Preview

In the realm of web development, a real-time clock plays a significant role by providing users with the current time and date. It serves as a valuable feature for various applications, including scheduling systems, countdown timers, and live data updates. JavaScript, being a versatile and powerful programming language, enables us to create dynamic clocks that continuously update themselves to display the accurate time.

In this comprehensive tutorial, we will delve into the process of creating a real-time clock using JavaScript. By leveraging the capabilities of the Date object and the precise measurement of milliseconds, we will construct a clock that not only displays the current time but also includes millisecond precision. This precision allows for an enhanced user experience and opens up possibilities for advanced time-based functionalities in your web applications.

Throughout this tutorial, we will provide step-by-step instructions accompanied by clear and concise explanations. You will gain a solid understanding of how to implement a real-time clock in JavaScript, and you will be able to customize it to suit your specific requirements. Whether you are a beginner or an experienced web developer, this tutorial will equip you with the knowledge and skills needed to integrate a dynamic clock seamlessly into your projects.

So, let's embark on this journey to create a real-time clock that showcases the current time, including milliseconds, using the power of JavaScript. By the end of this tutorial, you will have a functional and visually appealing clock that can be incorporated into your websites or web applications with ease. Let's get started!

Join My Telegram Channel to Download the Projects Source Code: Click Here

Prerequisites:

Before starting this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. Additionally, you will need a code editor such as Visual Studio Code or Sublime Text to write and save your code.

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our Clock.

After creating the files just paste the following below codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.

Here is a breakdown of each element and its purpose:

1. <!DOCTYPE html>: This is the document type declaration and informs the browser that the document is an HTML5 document.

2. <html lang="en">: This is the root element of the HTML document. The lang attribute specifies the language of the document, which in this case is set to English ("en").

3. <head>: This element contains meta-information about the HTML document and includes links to external resources.

4. <title>JavaScript Clock with Date & Time</title>: This element sets the title of the webpage, which appears in the browser's title bar or tab.

5. <meta charset="UTF-8" />: This meta tag specifies the character encoding for the document. UTF-8 is a widely used character encoding that supports a wide range of characters from different languages.

6. <meta name="viewport" content="width=device-width" />: This meta tag sets the viewport properties for responsive web design. The width=device-width ensures that the webpage adapts to the width of the device's screen.

7. <link rel="stylesheet" href="styles.css" />: This link tag is used to include an external CSS file called "styles.css". It is used to apply styles and formatting to the HTML elements on the page.

8. <body>: This element represents the content of the webpage that is visible to the user.

9. <div id="timedate">: This is a container div that holds the elements related to displaying the date and time.

10. <div id="date"></div>: This empty div with the id "date" is where the date will be displayed.

11. <div id="time"></div>: This empty div with the id "time" is where the time will be displayed.

12. <script src="script.js"></script>: This script tag is used to include an external JavaScript file called "script.js". The JavaScript code inside this file will be responsible for updating the date and time dynamically on the webpage.

This is the basic structure of our Clock using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the clock is in place, the next step is to add styling to the clock using CSS.

Next, we will create our CSS file. In this file, we will use some basic CSS rules to create our clock.

Here is an explanation of each CSS rule:

1. body {background-color:#2d2d2d;}: This rule sets the background color of the element to #2d2d2d, which is a dark gray color.

2. #timedate: This rule targets the element with the id of "timedate".

  • font: small-caps lighter 43px/150% "Segoe UI", Frutiger, "Frutiger Linotype", "Dejavu Sans", "Helvetica Neue", Arial, sans-serif;: This line sets the font properties for the element. It specifies that the font should be displayed in small capitals, with a lighter weight, a font size of 43 pixels, and a line height of 150%. It also provides a list of fallback fonts in case the preferred fonts are not available on the user's system.
  • text-align: left;: This rule sets the alignment of the text inside the element to the left.
  • width: 50%;: This rule sets the width of the element to 50% of its containing element. This allows the element to take up half of the available width on the webpage.
  • margin: 40px auto;: This rule sets the top and bottom margins of the element to 40 pixels and horizontally centers the element using auto for left and right margins.
  • color: #fff;: This rule sets the text color inside the element to white.
  • border-left: 3px solid #ed1f24;: This rule adds a left border to the element. The border has a width of 3 pixels, a solid line style, and a color of #ed1f24, which is a shade of red.
  • padding: 20px;: This rule adds 20 pixels of padding to the content inside the element. Padding creates space between the content and the border.

This will give our clock an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

body {background-color:#2d2d2d;}

#timedate {
  font: small-caps lighter 43px/150% "Segoe UI", Frutiger, "Frutiger Linotype", "Dejavu Sans", "Helvetica Neue", Arial, sans-serif;
  text-align:left;
  width: 50%;
  margin: 40px auto;
  color:#fff;
  border-left: 3px solid #ed1f24;
  padding: 20px;
} 

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript.

The given JavaScript code defines a function called updateClock() that is responsible for updating a clock with the current date and time on a webpage. Here is a breakdown of the code:

1. var now = new Date();: This line creates a new Date object and assigns it to the variable now. This object represents the current date and time.

2. The next few lines extract various components from the now object to get the hours, minutes, seconds, milliseconds, and month.

3. var month = now.toLocaleString('default', { month: 'long' });: This line uses the toLocaleString() method to get the full name of the month based on the default locale. It assigns the month name to the variable month.

4. The following line constructs the time string by concatenating the hours, minutes, seconds, and milliseconds together, separated by colons and a dot. The addZeroPadding() and addZeroPaddingMilliseconds() functions are used to add leading zero padding to ensure the numbers are displayed with two digits.

5. Similarly, the date string is constructed by combining the month name, day of the month, and year.

6. The next two lines update the content of the HTML elements with the ids date and time by setting their innerHTML properties to the date and time strings, respectively.

7. setTimeout(updateClock, 1);: This line schedules the updateClock() function to be called again after 1 millisecond using the setTimeout() function. This creates a loop that continuously updates the clock.

9. The next two functions, addZeroPadding() and addZeroPaddingMilliseconds(), are utility functions that add leading zero padding to numbers less than 10 or less than 100, respectively.

9. Finally, the updateClock() function is called once at the end to start the clock immediately.

Create a JavaScript file with the name of script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document, so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

function updateClock() {
  var now = new Date();

  var hours = now.getHours();
  var minutes = now.getMinutes();
  var seconds = now.getSeconds();
  var milliseconds = now.getMilliseconds();
  var month = now.toLocaleString('default', { month: 'long' }); // Get month name

  var time = hours + ':' + addZeroPadding(minutes) + ':' + addZeroPadding(seconds) + '.' + addZeroPaddingMilliseconds(milliseconds);
  var date = month + ' ' + now.getDate() + ', ' + now.getFullYear();

  document.getElementById('date').innerHTML = date;
  document.getElementById('time').innerHTML = time;

  setTimeout(updateClock, 1); // Update every millisecond
}

// Function to add zero padding to numbers less than 10
function addZeroPadding(num) {
  return (num < 10 ? '0' : '') + num;
}

// Function to add zero padding to milliseconds less than 100
function addZeroPaddingMilliseconds(num) {
  return (num < 100 ? '0' : '') + (num < 10 ? '0' : '') + num;
}

// Start the clock
updateClock();

Final Output:

create a real-time clock in javascript with date and milliseconds.gif

Conclusion:

Congratulations on completing this tutorial on creating a real-time clock in JavaScript with date and milliseconds! Throughout this journey, we explored the essential steps required to implement a dynamic clock that accurately displays the current time and includes millisecond precision.

By leveraging the Date object in JavaScript, we were able to retrieve the current date and time. We learned how to extract hours, minutes, seconds, and milliseconds from the Date object and update the clock display in real-time. Additionally, we addressed the issue of leading zeroes for single-digit values, ensuring a consistent and visually appealing clock display.

Furthermore, we incorporated a refreshing mechanism that allowed the clock to update itself every millisecond, ensuring maximum accuracy. This not only provided users with a real-time experience but also opened up possibilities for implementing time-based functionalities in your web applications.

Remember, this tutorial serves as a foundation for creating a real-time clock, and there are various ways to enhance and customize it further. You can explore styling options to match the clock with your website's design, add additional functionalities such as time zone conversion or countdown timers, or integrate it with other components of your web application.

By following this tutorial, you have gained valuable insights into JavaScript programming, particularly in handling date and time-related operations. These skills can be applied to various other web development projects where time-based functionalities are required.

We hope this tutorial has empowered you to create captivating and functional clocks that enrich the user experience of your web applications. As you continue to explore and expand your knowledge, don't hesitate to refer back to this tutorial or seek additional resources to deepen your understanding.

Thank you for joining us on this journey to create a real-time clock in JavaScript. Happy coding!

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺